#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_btn_load_clicked()
{
    filePath=QFileDialog::getOpenFileName(this,"选择配置文件","",
                                          "*.dat");
    if(filePath.isEmpty())
        return;

    QFile file(filePath);
    file.open(QFile::ReadOnly);

    QDataStream in(&file);
    QString entry,host,user,passwd,dbName;
    qint32 port;
    in
            >> entry >> host >> port
            >> user >> passwd >> dbName;

    ui->entry->setText(entry);
    ui->host->setText(host);
    ui->port->setValue(port);
    ui->user->setText(user);
    ui->passwd->setText(passwd);
    ui->dbName->setText(dbName);
}

void Widget::saveAction(const QString &entry,
                        const QString &host,
                        int port,
                        const QString &user,
                        const QString &passwd,
                        const QString &dbName,
                        const QString &filePath)
{
    QFile file(filePath);
    file.open(QFile::WriteOnly);

    QDataStream out(&file);
    out
            << entry << host << (qint32)port
            << user << passwd << dbName;

    file.close();

    QMessageBox::information(this,"操作完成","文件已写入：\n" + filePath);
}

void Widget::on_btn_save_clicked()
{
    auto entry=ui->entry->text().trimmed();
    auto host=ui->host->text().trimmed();
    auto port=ui->port->value();
    auto user=ui->user->text().trimmed();
    auto passwd=ui->passwd->text().trimmed();
    auto dbName=ui->dbName->text().trimmed();

    if(filePath.isEmpty())
    {
        filePath=QFileDialog::getSaveFileName(this,"选择要保存的文件","",
                                              "*.dat");
    }

    if(filePath.isEmpty())
        return;

    saveAction(entry,host,port,user,passwd,dbName,filePath);
}

void Widget::on_btn_saveAs_clicked()
{
    auto entry=ui->entry->text().trimmed();
    auto host=ui->host->text().trimmed();
    auto port=ui->port->value();
    auto user=ui->user->text().trimmed();
    auto passwd=ui->passwd->text().trimmed();
    auto dbName=ui->dbName->text().trimmed();

    filePath=QFileDialog::getSaveFileName(this,"选择要保存的文件","",
                                          "*.dat");

    if(filePath.isEmpty())
        return;

    saveAction(entry,host,port,user,passwd,dbName,filePath);
}
